package com.gistone.commis.api.restController;

import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.dto.Option;
import com.gistone.commis.dto.Options;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.*;
import com.gistone.commis.query.QueryProperty;
import com.gistone.commis.util.AuditState;
import com.gistone.commis.util.DataTablePageUtil;
import com.gistone.commis.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageRowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController("apiPropertyController")
@RequestMapping("api/property")
public class PropertyController {

    private static final Logger logger = LoggerFactory.getLogger(PropertyController.class);


    @Autowired
    private PropertyMapper propertyMapper;
    @Autowired
    private PropertyTypeMapper propertyTypeMapper;

    @Autowired
    private PropertyLogMapper propertyLogMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;


    /**
     * 根据id获取资产信息
     *
     * @param id
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public Property property(@PathVariable int id) {
        Property property = propertyMapper.selectByPrimaryKey(id);
        return property;
    }

    /**
     * 新建资产信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public EditorResult<Property> create(HttpServletRequest request, HttpServletResponse response) {
        Property property = new Property();
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        property.setApplyUserId(user.getUserId());
        property.setRegisterTime(new Date());
        EditorResult<Property> propertyEditorResult = new EditorResult<>();
        List<FieldError> fieldErrorList = new ArrayList<>();
//        house.setHouseId(houseId);
        getProperty(request, "data[0][", property, fieldErrorList);
        if (null == property.getCommunityId()) {
            property.setCommunityId(user.getCommunity().getCommunityId());
        }
        if (null == property.getDepartId()) {
            property.setDepartId(1);
        }


        if (fieldErrorList.size() > 0) {
            logger.error("字段格式错误");
            propertyEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return propertyEditorResult;
        }


        //添加，审核用户id，就为父级用户id
        property.setAuditorId(user.getParentId());
        property.setAddAuditState(AuditState.WATING);
        property.setIsScrap(false);

        int no;
        try {
            no = propertyMapper.insertSelective(property);
        } catch (Exception e) {
            logger.error("字段错误");
            fieldErrorList.add(new FieldError("propertyCode", "资产编号不能重复"));
            propertyEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return propertyEditorResult;
        }
        if (no > 0) {
            List<Property> data = new ArrayList<>();
            data.add(propertyMapper.selectByPrimaryKey(property.getPropertyId()));
            propertyEditorResult.setData(data);

            PropertyLog propertyLog = new PropertyLog(property, new Date(), user.getUserId());

            if (propertyLogMapper.insertSelective(propertyLog) > 0) {
                logger.info("保存资产日志信息成功");
            } else {
                logger.info("保存资产日志信息失败");
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

            }
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return propertyEditorResult;

    }

    /**
     * 批量修改资产信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = houseIdStr.split(",");
        EditorResult<Property> propertyEditorResult = new EditorResult<>();
        List<Property> data = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int propertyId = Integer.valueOf(arr[i]);
            Property property = new Property();
            property.setPropertyId(propertyId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            property.setApplyUserId(user.getUserId());
            getProperty(request, "data[" + propertyId + "][", property, fieldErrorList);
            if (fieldErrorList.size() > 0) {
                logger.error("字段错误");
                propertyEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return propertyEditorResult;
            }
            int no;
            try {
                no = propertyMapper.updateByPrimaryKeySelective(property);
            } catch (Exception e) {
                logger.error("字段错误");
                fieldErrorList.add(new FieldError("propertyCode", "资产编号不能重复"));
                propertyEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return propertyEditorResult;
            }
            if (no > 0) {
                System.out.println("property---" + property);
                Property p = propertyMapper.selectByPrimaryKey(propertyId);

                data.add(p);
                PropertyLog propertyLog = new PropertyLog(p, new Date(), user.getUserId());

                if (propertyLogMapper.insertSelective(propertyLog) > 0) {
                    logger.info("保存资产日志信息成功");
                } else {
                    logger.info("保存资产日志信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        propertyEditorResult.setData(data);
        return propertyEditorResult;


    }


    /**
     * 资产删除
     * 通过资产ID批量删除房屋信息， id以,号分割
     *
     * @param propertyIdStr
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String propertyIdStr, HttpServletResponse response) {
        String[] arr = propertyIdStr.split(",");
        EditorResult<Property> propertyEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int propertyId = Integer.valueOf(arr[i]);
            Property property = new Property();
            property.setIsDelete(1);
            property.setPropertyId(propertyId);
            if (propertyMapper.updateByPrimaryKeySelective(property) > 0) {
                System.out.println("删除" + propertyId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return propertyEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<Property> pageDatatables(HttpServletRequest request, QueryProperty property) {
//		HttpSession httpSession = request.getSession();
//		User user = (User) httpSession.getAttribute("userInfo");
//		logger.info("用户信息：" + user.toString());
//		int community_id = user.getCommunity().getCommunityId();
//		property.setCommunityId(community_id);

        List<Community> communities = communityMapper.findCommunitys();
        Options os = new Options();
        List<Option> optionList = new ArrayList<>();
        for (Community community : communities) {

            Option option = new Option();
            option.setLabel(community.getCommunityName());
            option.setValue(community.getCommunityId());
            optionList.add(option);


        }
        os.setCommunityId(optionList);
        List<Depart> departs = departMapper.findDeparts();
        optionList = new ArrayList<>();
        for (Depart depart : departs) {

            Option option = new Option();
            option.setLabel(depart.getDepartName());
            option.setValue(depart.getDepartId());
            optionList.add(option);


        }

        os.setDepartId(optionList);

        List<PropertyType> propertyTypes = propertyTypeMapper.findPropertyTypes();
        optionList = new ArrayList<>();
        for (PropertyType propertyType : propertyTypes) {

            Option option = new Option();
            option.setLabel(propertyType.getTypeName());
            option.setValue(propertyType.getTypeId());
            optionList.add(option);


        }
        os.setTypeId(optionList);

        DataTablePageUtil<Property> dataTable = new DataTablePageUtil<>(request);

        property.setIsDelete(0);
        PageHelper.startPage(dataTable.getPage_num(), 10);
        List<Property> list = propertyMapper.selectSelective(property);
        PageInfo<Property> pageInfo = new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面

        return dataTable;

    }


    private void getProperty(HttpServletRequest request, String prefix, Property property, List<FieldError> fieldErrorList) {
        if (null != request.getParameter(prefix + "communityId]") && !request.getParameter(prefix + "communityId]").isEmpty()) {
            property.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


        }
        if (null != request.getParameter(prefix + "departId]") && !request.getParameter(prefix + "departId]").isEmpty()) {
            property.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));


        }
        if (null != request.getParameter(prefix + "typeId]")) {
            try {
                property.setTypeId(Integer.valueOf(request.getParameter(prefix + "typeId]")));
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("typeId", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }
        }
        if (null != request.getParameter(prefix + "propertyCode]")) {

            property.setPropertyCode(request.getParameter(prefix + "propertyCode]"));

        }

        property.setPropertyName(request.getParameter(prefix + "propertyName]"));
        property.setPropertyBrand(request.getParameter(prefix + "propertyBrand]"));
        property.setSpecificationType(request.getParameter(prefix + "specificationType]"));
        property.setUseStatus(request.getParameter(prefix + "useStatus]"));
        property.setPropertyAdd(request.getParameter(prefix + "propertyAdd]"));
        property.setConfigurationUnit(request.getParameter(prefix + "configurationUnit]"));

        property.setRemarks(request.getParameter(prefix + "remarks]"));
        if (null != request.getParameter(prefix + "deployTime]")) {
            property.setDeployTime(request.getParameter(prefix + "deployTime]"));
        }

        if (null != request.getParameter(prefix + "count]")) {
            try {
                property.setCount(Integer.valueOf(request.getParameter(prefix + "count]")));
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("count", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }
        }
        if (null != request.getParameter(prefix + "serialNumber]")) {
            property.setSerialNumber(request.getParameter(prefix + "serialNumber]"));
        }


        if (null != request.getParameter(prefix + "addAuditState]")) {
            try {
                int addState = Integer.valueOf(request.getParameter(prefix + "addAuditState]"));
                if (addState == 1) {//通过
                    property.setAddAuditState(1);
                    property.setPropertyState(1);//通过就为在用状态
                } else if (addState == 2) { //不通过
                    property.setAddAuditState(2);
                    property.setPropertyState(-1);//-1 代表不通过
                }
            } catch (NumberFormatException e) {
                logger.error("数量格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("addAuditState", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }

        if (null != request.getParameter(prefix + "delAuditState]")) {
            try {
                int delState = Integer.valueOf(request.getParameter(prefix + "delAuditState]"));
                if (delState == 1) {//通过
                    property.setDelAuditState(1);
                    property.setPropertyState(3);//通过就为报废状态
                } else if (delState == 2) { //不通过就删除数据
                    property.setDelAuditState(2);
                    property.setPropertyState(1);//不通过就为在用状态
                }
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("addAuditState", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }

        if (null != request.getParameter(prefix + "propertyState]")&&!request.getParameter(prefix + "propertyState]").isEmpty()) {
            try {
                int propertyState = Integer.valueOf(request.getParameter(prefix + "propertyState]"));
                property.setPropertyState(propertyState);
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("propertyState", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }
        if (null != request.getParameter(prefix + "isDelete]")&&!request.getParameter(prefix + "isDelete]").isEmpty()) {
            System.out.println("--d---"+request.getParameter(prefix + "isDelete]"));
            try {
                int isDelete = Integer.valueOf(request.getParameter(prefix + "isDelete]"));
                property.setIsDelete(isDelete);
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为整形数字");
                FieldError fieldError = new FieldError("isDelete", "格式不正确，必须为整形数字");
                fieldErrorList.add(fieldError);
            }

        }


    }


}
